/*
 * PanelTowerSelector.java
 *
 * Created on December 9, 2007, 2:28 PM
 * 
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package hextd.UI;

import hextd.HexTD;
import hextd.hex.Hex;
import hextd.hex.HexBase;
import hextd.tower.Tower;
import hextd.tower.TowerFactory;
import hextd.core.ContextListener;
import hextd.core.ContextNormal;
import hextd.core.ContextPlayer;
import hextd.tower.TowerFactory.type;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JToggleButton;
import javax.swing.border.LineBorder;

/**
 *
 * @author  hylke
 */
public class PanelTowerSelector extends javax.swing.JPanel implements ContextListener {

	private BufferedImage[] images;
	private BufferedImage[] imagesDisabled;
	private JToggleButton[] buttons;
	private String[] infoText;
	private float[] towerRanges;
	private ContextNormal context;
	private HexTD mainApp;
	private ArrayList<TowerFactory.type> towerTypes;
	private boolean placing = false;
	private int buttonSize = 32;

	/** Creates new form PanelTowerSelector */
	public PanelTowerSelector() {
	}

	public void doInit(ContextNormal c, HexTD mainApp) {
		this.context = c;
		this.mainApp = mainApp;

		initComponents();
		this.towerTypes = new ArrayList<TowerFactory.type>();
		this.towerTypes.add(TowerFactory.type.greenOne);
		this.towerTypes.add(TowerFactory.type.redOne);
		this.towerTypes.add(TowerFactory.type.yellowOne);
		this.towerTypes.add(TowerFactory.type.blueOne);
		this.towerTypes.add(TowerFactory.type.firecontrol);
		this.towerTypes.add(TowerFactory.type.greenTwo);
		this.towerTypes.add(TowerFactory.type.redTwo);
		this.towerTypes.add(TowerFactory.type.yellowTwo);
		this.towerTypes.add(TowerFactory.type.blueTwo);
		this.towerTypes.add(TowerFactory.type.upgradeDamage);
		this.towerTypes.add(TowerFactory.type.greenThree);
		this.towerTypes.add(TowerFactory.type.redThree);
		this.towerTypes.add(TowerFactory.type.yellowThree);
		this.towerTypes.add(TowerFactory.type.blueThree);
		this.towerTypes.add(TowerFactory.type.upgradeRange);

		this.images = new BufferedImage[this.towerTypes.size()];
		this.imagesDisabled = new BufferedImage[this.towerTypes.size()];
		this.buttons = new JToggleButton[this.towerTypes.size()];
		this.infoText = new String[this.towerTypes.size()];
		this.towerRanges = new float[this.towerTypes.size()];


		this.makeButtons();

		ContextNormal tempContext = new ContextNormal(null);
		ScaledCanvas sc = new ScaledCanvas() {

			float paintScale, strokeScale, offsetX, offsetY, hexPaintWidth;

			@Override
			public float getPaintScale() {
				return paintScale;
			}

			@Override
			public float getStrokeScale() {
				return strokeScale;
			}

			@Override
			public void setPaintScale(float scale) {
				paintScale = scale;
			}

			@Override
			public void setStrokeScale(float scale) {
				strokeScale = scale;
			}

			@Override
			public float getOffsetX() {
				return offsetX;
			}

			@Override
			public void setOffsetX(float offsetX) {
				this.offsetX = offsetX;
			}

			@Override
			public float getOffsetY() {
				return offsetY;
			}

			@Override
			public void setOffsetY(float offsetY) {
				this.offsetY = offsetY;
			}

			@Override
			public float getHexPaintWidth() {
				return hexPaintWidth;
			}

			@Override
			public void setHexPaintWidth(float hexPaintWidth) {
				this.hexPaintWidth = hexPaintWidth;
			}
		};
		tempContext.setScaledCanvas(sc);

		tempContext.colors = c.colors;
		tempContext.setContextUrl(c.getContextUrl());
		sc.setPaintScale((float) this.buttonSize / 2f);
		sc.setStrokeScale(sc.getPaintScale() / 40f);
		float hexFloatWidth = (float) Math.sin(Math.PI / 3.0);
		sc.setHexPaintWidth(hexFloatWidth * sc.getPaintScale());
		sc.setOffsetX(sc.getPaintScale() - sc.getHexPaintWidth());
		sc.setOffsetY(0);

		Hex tempHex = new HexBase(0, 0, tempContext, true, true);
		tempHex.resetScale();

		for (int i = 0; i < this.towerTypes.size(); i++) {
			this.images[i] = new BufferedImage(this.buttonSize, this.buttonSize, BufferedImage.TYPE_INT_RGB);
			this.imagesDisabled[i] = new BufferedImage(this.buttonSize, this.buttonSize, BufferedImage.TYPE_INT_RGB);
			Tower tempTower = TowerFactory.createTower(this.towerTypes.get(i), tempContext, tempHex, -1, 0);
			this.infoText[i] = tempTower.getInfoString();
			this.imageFromTower(this.images[i], tempHex, tempTower, false);
			this.imageFromTower(this.imagesDisabled[i], tempHex, tempTower, true);
			this.buttons[i].setIcon(new ImageIcon(this.images[i]));
			this.buttons[i].setDisabledIcon(new ImageIcon(this.imagesDisabled[i]));
			this.towerRanges[i] = tempTower.getRangeBase();
		}

		this.context.addContextListener(this);
	}

	private void makeButtons() {
		GridBagConstraints gridBagConstraints;
		JToggleButton tempToggle;
		for (int i = 0; i < this.towerTypes.size(); i++) {
			tempToggle = new JToggleButton();
			tempToggle.setBorder(new LineBorder(context.colors.getColorForeGroundPale()));
			tempToggle.setBackground(this.context.colors.getColorBackGround());
			tempToggle.setForeground(this.context.colors.getColorForeGround());
			this.buttons[i] = tempToggle;
			tempToggle.setMargin(new java.awt.Insets(1, 1, 1, 1));
			final int n = i;
			tempToggle.addActionListener(new java.awt.event.ActionListener() {

				@Override
				public void actionPerformed(java.awt.event.ActionEvent evt) {
					doPlace(n);
				}
			});
			tempToggle.addMouseListener(new java.awt.event.MouseAdapter() {

				@Override
				public void mouseEntered(java.awt.event.MouseEvent evt) {
					mouseOver(n);
				}
			});
			gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = n % 5;
			gridBagConstraints.gridy = n / 5;
			//gridBagConstraints.weightx = 0.01;
			//gridBagConstraints.weighty = 0.01;
			gridBagConstraints.insets = new Insets(2, 2, 2, 2);
			add(tempToggle, gridBagConstraints);
		}
	}

	private void imageFromTower(BufferedImage i, Hex h, Tower t, boolean disabled) {
		Graphics2D g2 = i.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		h.paintBase(g2, g2);
		t.paint(g2, 0);
		g2.setColor(new Color(0, 0, 0, 192));
		if (disabled) {
			g2.fillRect(0, 0, i.getWidth(), i.getHeight());
		}
		g2.dispose();
	}

	public void startPlacing(TowerFactory.type t, float r) {
		this.placing = true;
		this.mainApp.startPlacing(t, r);
	}

	public void stopPlacing() {
		this.untoggleAll();
		this.placing = false;
	}

	/**
	 * Set the tower-buy-buttons to the correct ones.
	 */
	public void mapChanged() {
		for (int i = 0; i < buttons.length; i++) {
			type ttype = towerTypes.get(i);
			buttons[i].setVisible(context.newTowerAllowed(ttype, context.getLocalPlayerId()));
		}
	}

	@Override
	public void moneyChanged(ContextPlayer player) {
		if (player == context.getLocalPlayer()) {
			for (int i = 0; i < buttons.length; i++) {
				if (buttons[i].isVisible()) {
					type ttype = towerTypes.get(i);
					buttons[i].setEnabled(player.canPay(ttype.price, true));
				}
			}
		}
	}

	@Override
	public void livesChanged(ContextPlayer player) {
	}

	@Override
	public void interestChanged(ContextPlayer player) {
	}

	private void untoggleAll() {
		for (int i = 0; i < this.buttons.length; i++) {
			this.buttons[i].setSelected(false);
		}
	}

	public void doPlace(int i) {
		type ttype = towerTypes.get(i);
		if (context.newTowerAllowed(ttype, context.getLocalPlayerId())) {
			mouseOver(i);
			untoggleAll();
			buttons[i].setSelected(true);
			mainApp.setInfoText(infoText[i], true);
			startPlacing(towerTypes.get(i), towerRanges[i]);
		}
	}

	private void mouseOver(int i) {
		if (!placing) {
			mainApp.setInfoText(this.infoText[i], false);
		}
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setBackground(this.context.colors.getColorBackGround());
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Towers", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), this.context.colors.getColorForeGround()));
        setForeground(this.context.colors.getColorForeGround());
        setLayout(new java.awt.GridBagLayout());
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
